•  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
r1 vs r2
......
3535== 구성 요소 ==
3636
3737=== 상태 정의 - enum ===
38{{{#!syntax solidity
38{{{
3939enum Stage {
4040 Created,
4141 Bidding,
......
4848내부적으로 {{{uint8}}}로 저장된다. 정의되지 않은 값으로의 캐스팅은 revert된다. (Solidity 0.8+)[*4 Solidity Documentation. [[https://docs.soliditylang.org/en/latest/types.html#enums|Enums]]. docs.soliditylang.org.]
4949
5050=== 상태 검증 - modifier ===
51{{{#!syntax solidity
51{{{
5252modifier atStage(Stage expected) {
5353 require(currentStage == expected, "Invalid stage");
5454 _;
......
5959
6060=== 전이 함수 ===
6161'''선형 전이''' - 순서대로만 진행:
62{{{#!syntax solidity
62{{{
6363function nextStage() internal {
6464 currentStage = Stage(uint(currentStage) + 1);
6565}
6666}}}
6767
6868'''명시적 전이''' - 허용된 경로만:
69{{{#!syntax solidity
69{{{
7070function transitionTo(Stage next) internal {
7171 require(allowedTransitions[currentStage][next]);
7272 currentStage = next;
......
7676=== 시간 기반 전이 - timedTransition ===
7777블록체인에는 cron이 없으므로 다음 트랜잭션 호출 시 시간 경과를 검사한다.[*5 Solidity Documentation. [[https://docs.soliditylang.org/en/latest/common-patterns.html#state-machine|Common Patterns: State Machine]]. docs.soliditylang.org.]
7878
79{{{#!syntax solidity
79{{{
8080modifier timedTransition() {
8181 if (currentStage == Stage.Bidding
8282 && block.timestamp >= createdAt + BIDDING_DURATION)
......
9393}}}
9494
9595=== 이벤트 ===
96{{{#!syntax solidity
96{{{
9797event StageChanged(Stage indexed from, Stage indexed to, address indexed triggeredBy);
9898}}}
9999
......
109109=== 비선형 전이 - 전이 테이블 ===
110110분기·복귀가 있는 워크플로우에서 사용한다. 허용된 전이를 mapping으로 정의한다.[*1]
111111
112{{{#!syntax solidity
112{{{
113113mapping(Stage => mapping(Stage => bool)) private allowedTransitions;
114114
115115constructor() {
......
124124=== 비트마스크 최적화 ===
125125이중 mapping은 검증당 SLOAD 2회가 필요하다. 비트마스크를 사용하면 SLOAD 1회 + 비트 연산으로 줄일 수 있다.[*6 Ethereum Yellow Paper. [[https://ethereum.github.io/yellowpaper/paper.pdf|Ethereum: A Secure Decentralised Generalised Transaction Ledger]]. Appendix G. Fee Schedule.]
126126
127{{{#!syntax solidity
127{{{
128128mapping(Stage => uint8) private transitionMap;
129129
130130// AwaitingPayment -> Funded(bit 1) 허용
......
168168 * [[Checks-Effects-Interactions 패턴]] - 상태 변경 후 외부 호출. State Machine의 전이 보안에 필수적이다.
169169 * [[Pull over Push 패턴]] - {{{withdraw()}}} 패턴. 상태 전이와 자금 인출을 분리하여 안전성을 높인다.
170170
171
171172== 관련 문서 ==
172173 * [[블록체인]]
173174 * [[스마트 컨트랙트]]
174175 * [[Solidity]]
175176 * [[이더리움]]
176177 * [[유한 상태 기계]]
177178 * [[디자인 패턴]]